package cn.sykj.car.controller;


import cn.sykj.car.common.ResponseBean;
import cn.sykj.car.common.StatusCode;
import cn.sykj.car.entity.Operation;
import cn.sykj.car.service.IOperationService;
import cn.sykj.car.service.IUsersService;
import cn.sykj.car.utils.Utils;
import cn.sykj.car.vo.OperationVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 操作权限 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"操作权限 前端控制器"})
@RestController
@RequestMapping("/operation")
public class OperationController extends BaseController {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(OperationController.class);

    @Resource
    private IOperationService iOperationService;

    @Resource
    private IUsersService iUsersService;

    /**
     * 添加权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:create")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseBean insertOperation(
            @RequestBody OperationVO operationVOParam, HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        // 插入
        Operation operation = new Operation();

        // 权限名称
        if (Utils.notEmpty(operationVOParam.getOperationName())) {
            operation.setOperationName(operationVOParam.getOperationName());
        }


        String codePre = "";
        String codeSuf = "";
        // 权限前缀String
        if (Utils.notEmpty(operationVOParam.getCodePre())) {
            codePre = operationVOParam.getCodePre();
        }

        // 权限后缀List<String>
        if (Utils.notEmpty(operationVOParam.getCodeSuf())) {
            List<String> suffixs = operationVOParam.getCodeSuf();
            for (String suffixCode : suffixs) {
                codeSuf += suffixCode + ",";
            }
        }

        if (Utils.notEmpty(codePre) && Utils.notEmpty(codeSuf)) {
            codeSuf = codeSuf.substring(0, codeSuf.length() - 1);
            operation.setPermissionCode(codePre + ":" + codeSuf);
        }

        this.writeLog("添加权限");
        iOperationService.insertOperation(operation);
        return new ResponseBean(StatusCode.OK, null);
    }


    /**
     * 修改权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:edit")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseBean updateOperation(
            @RequestBody OperationVO operationVOParam, HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        if (Utils.notEmpty(operationVOParam.getId())) {

            // 修改菜单
            Operation operation = new Operation();
            if (Utils.notEmpty(operationVOParam.getOperationName())) {
                operation.setOperationName(operationVOParam.getOperationName());
            }

            String codePre = "";
            String codeSuf = "";
            // 权限前缀String
            if (Utils.notEmpty(operationVOParam.getCodePre())) {
                codePre = operationVOParam.getCodePre();
            }

            // 权限后缀List<String>
            if (Utils.notEmpty(operationVOParam.getCodeSuf())) {
                List<String> suffixs = operationVOParam.getCodeSuf();
                for (String suffixCode : suffixs) {
                    codeSuf += suffixCode + ",";
                }
            }

            if (Utils.notEmpty(codePre) && Utils.notEmpty(codeSuf)) {
                codeSuf = codeSuf.substring(0, codeSuf.length() - 1);
                operation.setPermissionCode(codePre + ":" + codeSuf);
            }

            operation.setId(operationVOParam.getId());
            iOperationService.updateOperation(operation);
            this.writeLog("修改权限");
            return new ResponseBean(StatusCode.OK, null);
        } else {
            return new ResponseBean(StatusCode.OK_FAIL, null);
        }

    }

    /**
     * 删除权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除权限", notes = "登陆才能操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限id", dataType = "Integer", paramType = "query", required = true),
    })
    @RequiresAuthentication
    @RequiresPermissions("operation:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public ResponseBean deleteOperation(
            @PathVariable Integer id,HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);


        // 删除
        Operation operation = new Operation();
        operation.setId(id);

        iOperationService.deleteOperation(operation);
        this.writeLog("删除权限");
        return new ResponseBean(StatusCode.OK, null);

    }


    /**
     * 查看权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:view")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public ResponseBean selectOperation(
            @RequestBody OperationVO operationVOParam,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);


        // 查询全部权限（翻页查询）
        if (pageSize == 0) {
            pageSize = Integer.MAX_VALUE;
        }

        Operation searchOperation = new Operation();
        if (Utils.notEmpty(operationVOParam.getOperationName())) {
            searchOperation.setOperationName(operationVOParam.getOperationName());
        }
        if (Utils.notEmpty(operationVOParam.getPermissionCode())) {
            searchOperation.setPermissionCode(operationVOParam.getPermissionCode());
        }

        Page<Operation> page = new Page(currentPage, pageSize);
        page = iOperationService.pageOperation(page, searchOperation);
        return new ResponseBean(StatusCode.OK, page);

    }

    /**
     * 查看权限下拉选
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看权限下拉选", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:view")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResponseBean selectOperationByList(

    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        QueryWrapper<Operation> queryWrapper = new QueryWrapper();
        queryWrapper.select(Operation.ID,Operation.OPERATION_NAME);
        List<Operation> list = iOperationService.list();

        return new ResponseBean(StatusCode.OK, list);
    }
}
